package com.dzu.easy;

/**
 * @author ZhaoDong
 * @date 2023/2/23 9:58
 * @description 704. 二分查找
 */
public class Test704 {
    public static void main(String[] args) {

        System.out.println(search(new int[]{0, 3, 5, 7, 99}, 3));
    }


    // 左闭右闭
    public static int search(int[] nums, int target) {

        int left = 0;
        int right = nums.length - 1;
        int middle;
        while (left <= right) {
            middle = (left + right) / 2;
            if (nums[middle] > target) {
                right = middle - 1;
            } else if (nums[middle] < target) {
                left = middle + 1;
            } else {
                return middle;
            }
        }
        return -1;
    }

    // 左闭右开
    public static int search2(int[] nums, int target) {

        int left = 0;
        int right = nums.length;
        int middle;
        while (left < right) {
            middle = (left + right) / 2;
            if (nums[middle] > target) {
                right = middle;
            } else if (nums[middle] < target) {
                left = middle + 1;
            } else {
                return middle;
            }
        }
        return -1;
    }
}
